<template>
	<view class="wrapper">
		<u-navbar :title="title" @leftClick="goBack" bgColor="#F6F6F6" titleStyle="font-weight: 500; color: #000000;"
			:placeholder="true">
			<view class="u-nav-slot" :class="{ 'u-nav__active': isCanNext }" slot="right" @click="nextHandle">
				{{ nextBtn }}
			</view>
		</u-navbar>

		<!-- 选择人数 -->
		<view class="select-number">
			{{ newSelectList.length }}/{{ list.length }}
		</view>

		<!-- 搜索框 -->
		<view class="search-content">
			<u-input :placeholder="$t('index.Search')" v-model="searchValue" placeholderClass="placeholderClass" border="none"
				inputAlign="center" shape="circle" :customStyle="{
          background: '#fff',
          height: '76rpx',
          padding: '0 38rpx',
          'font-size': '26rpx',
        }"></u-input>
			<view class="iconfont icon-sousuo serch-icon" v-show="!searchValue"></view>
		</view>

		<!-- 已选择用户头像以及未选择用户时提示语区域 -->
		<view class="tip-content" v-if="newSelectList.length > 0">
			<scroll-view scroll-x="true" class="scroll-X">
				<view class="avatar" :class="'avatar' + index" v-for="(item, index) in newSelectList" :key="index">
					<image v-if="item.conversationType == 1 && isPeopleAvatarExit(item.info &&
              (item.info.avatarCompress ||
                item.info.showUserAvatar ||
                item.info.avatar))" :src="
              item.info &&
              (item.info.avatarCompress ||
                item.info.showUserAvatar ||
                item.info.avatar)
            " class="avatar-image" mode="aspectFill" />
					<view v-else-if="item.conversationType == 1" class="avatar-image avator-font-setting"
						:style="{ background: `${getDefaultColor(item.info.avatarColorCode)}`, fontSize: '30upx', fontWeight: '400' }">
						{{ formatUserName(item.info).slice(0, 1) }}</view>
					<image v-else-if="
              item.conversationType == 3 &&
              (item.info.avatarCompress || item.info.showAvatar)
            " :src="item.info.avatarCompress || item.info.showAvatar" class="avatar-image" mode="aspectFill" />
					<view class="avatar-image" v-else-if="item.conversationType == 3" :style="{
              background: `${
                item.info ? item.info.defaultColor || item.info.background : ''
              }`,
            }">
						{{
              item.info
                ? item.info.defaultName ||
                  (item.info.groupName && item.info.groupName.slice(0, 1))
                : ""
            }}
					</view>
				</view>
			</scroll-view>
		</view>

		<view class="tip-content tip-content-text" v-else>
			<view class="tip-content__text">
				{{ tipText }}
			</view>
		</view>

		<u-checkbox-group>
			<scroll-view scroll-top="0" scroll-y="true" class="scroll-Y">
				<view class="chat-content">
					<view v-for="(item, index) in list" :key="index" class="chat-line">
						<view class="chat-line__item" @click.stop="changeStateHandle(item)">
							<u-checkbox :checked="item.isSelect" :disabled="
                  isSingleSelect && newSelectList.length === 1 && !item.isSelect
                " shape="circle" activeColor="#61BDB2" :name="index" @change="changeStateHandle(item)">
							</u-checkbox>
							<image v-if="item.conversationType == 1 && isPeopleAvatarExit(item.info &&
              (item.info.avatarCompress ||
                item.info.showUserAvatar ||
                item.info.avatar))" :src="
                  item.info &&
                  (item.info.avatarCompress ||
                    item.info.showUserAvatar ||
                    item.info.avatar)
                " class="avatar-image" mode="aspectFill" />
							<view v-else-if="item.conversationType == 1" class="avatar-image avator-font-setting"
								:style="{ background: `${getDefaultColor(item.info.avatarColorCode)}`, fontSize: '30upx', fontWeight: '400' }">
								{{ formatUserName(item.info).slice(0, 1) }}</view>
							<image v-else-if="
                  item.conversationType == 3 &&
                  (item.info.avatarCompress || item.info.showAvatar)
                " :src="item.info.avatarCompress || item.info.showAvatar" class="avatar-image" mode="aspectFill" />
							<view class="avatar-image" v-else-if="item.conversationType == 3" :style="{
                  background: `${
                    item.info
                      ? item.info.defaultColor || item.info.background
                      : ''
                  }`,
                }">
								{{
                  item.info
                    ? item.info.defaultName ||
                      (item.info.groupName && item.info.groupName.slice(0, 1))
                    : ""
                }}
							</view>
							<text class="omit" style="flex: 1">{{
                item.conversationType == 1
                  ? formatUserName(item.info)
                  : item.info && item.info.groupName
              }}</text>
							<view class="dating-tag"
								:style="{color: getRoomKeyLabel(item).color,borderColor: getRoomKeyLabel(item).color}"
								v-if="item.info.moduleType != 0">
								{{ getRoomKeyLabel(item).label }}
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</u-checkbox-group>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import {
		getDefaultColor
	} from "@/utils/index.js";
	export default {
		data() {
			return {
				searchValue: "",
				newSelectList: [],
				type: "",
				tipText: "",
				title: "",
				nextBtn: "",
				isSingleSelect: false,
				otherParams: {},
				info: undefined,
				isToPage: false,
			};
		},
		computed: {
			...mapState(["chatList"]),
			// 能否执行下一步
			isCanNext() {
				return this.newSelectList.length > 0 ? true : false;
			},
			list() {
				if (!this.searchValue) {
					return this.chatList
						.map((item) => {
							item.isSelect = false;
							return item;
						})
						.filter((o) => {
							return o.info && Object.keys(o.info).length !== 0 && o.conversationType != 6;
						})
						.sort((a, b) => {
							return b.isTop - a.isTop;
						});
				} else {
					return this.chatList
						.map((item) => {
							item.isSelect = false;
							return item;
						})
						.filter((o) => {
							return (
								o.info && Object.keys(o.info).length !== 0 && o.conversationType != 6 &&
								(o.conversationType == 1 ?
									String(this.formatUserName(o.info)).match(this.searchValue) :
									o.conversationType == 3 ?
									String(o.info.groupName).match(this.searchValue) :
									false)
							);
						})
						.sort((a, b) => {
							return b.isTop - a.isTop;
						});
				}
			},
			filterId() {
				var ids = [];
				for (const key in this.$store.state.moduleGroupInfo) {
					if (
						this.$store.state.moduleGroupInfo[key] &&
						Array.isArray(this.$store.state.moduleGroupInfo[key])
					) {
						this.$store.state.moduleGroupInfo[key].map((item) => {
							ids.push(item.groupId);
						});
					}
				}
				return ids;
			},
		},
		watch: {
			"$store.state.selectChatOption": {
				handler: function(newVal, oldVal) {
					let data = JSON.parse(JSON.stringify(newVal));
          console.log('**************************', data)
					this.info = data?.info || (data.type == 3 ? [] : {});
					this.isSingleSelect = data?.isSingle || false;
					this.type = data.type;
					this.tipText = data.tipText;
					this.title = data.title;
					this.nextBtn = data.nextBtn || this.$t("index.Next");
				},
				deep: true,
				immediate: true,
			},
		},
		methods: {
			getDefaultColor,
			// 返回上一頁
			goBack() {
				if (getCurrentPages().length < 2) {
					uni.redirectTo({
						url: `/${uni.getStorageSync("prePagesUrl")}`,
					});
				} else {
					uni.navigateBack()
				}
				console.log(getCurrentPages(), 'getCurrentPages()');
			},
			// 点击next执行回调
			nextHandle() {
				console.log("next!!!", this.newSelectList, this.type);
				// 1 分享名片到聊天  2 单选转发  3 多选转发
				switch (this.type) {
					case 1: // 分享名片到聊天
						this.onShareCard({
							conversationType: this.newSelectList[0].conversationType,
							targetId: String(this.newSelectList[0].targetId),
						});
						break;
					case 2: // 单选转发
						this.onForward({
							conversationType: this.newSelectList[0].conversationType,
							targetId: String(this.newSelectList[0].targetId),
						});
						break;
					case 3: // 多选转发
						this.onMultipleForward({
							conversationType: this.newSelectList[0].conversationType,
							targetId: String(this.newSelectList[0].targetId),
						});
						break;
					default:
						break;
				}
			},
			// 改变选中状态回调
			changeStateHandle(val) {
				console.log(val, 'valvalvalvals');
				if (val.isDisabled) return;
				if (this.isSingleSelect && this.newSelectList.length === 1 && !val.isSelect) return;
				val.isSelect = !val.isSelect;
				if (val.isSelect) {
					this.newSelectList.push(val);
				} else {
					this.newSelectList = this.newSelectList.filter((item) => {
						return val.targetId !== item.targetId;
					});
				}
			},
			// 分享名片功能
			onShareCard(converObj) {
				const timestamp = new Date().getTime();
				// 定义消息投送目标会话
				const conversation = converObj;
				// 配置属性
				const options = {
					messageId: timestamp,
				};

				const message = new this.$RongIMLib.CardMessage({
					content: "",
					info: this.info,
				});

				this.sendMessage(conversation, message, options);
			},
			// 单选转发功能
			async onForward(converObj) {
				const timestamp = new Date().getTime();
				// 定义消息投送目标会话
				const conversation = converObj;
				// 配置属性
				const options = {
					messageId: timestamp,
				};
				const type = this.info.messageType;
				const message = this.createMsg(type, this.info);
				this.sendMessage(conversation, message, options);
			},
			// 多选转发功能
			async onMultipleForward(converObj) {
				for (const key in this.info) {
					const timestamp = new Date().getTime();
					// 定义消息投送目标会话
					const conversation = converObj;
					// 配置属性
					const options = {
						messageId: timestamp,
					};
					const type = this.info[key].messageType;
					const message = this.createMsg(type, this.info[key]);
					if (Number(key) === Number(this.info.length - 1)) {
						this.isToPage = true
					}
					this.sendMessage(conversation, message, options);
				}
			},
			// 构建转发的消息实例
			createMsg(type, item) {
				let message;
				switch (type) {
					case "OL:Recall":
					case "RC:TxtMsg":
						message = new this.$RongIMLib.TextMessage({
							content: item.content.content,
						});
						break;
					case "RC:ImgMsg":
						message = new this.$RongIMLib.ImageMessage({
							content: item.content.content, // 图片缩略图，应为 Base64 字符串，且不可超过 80KB
							imageUri: item.content.imageUri, // 图片的远程访问地址
						});
						break;
					case "RC:SightMsg":
						message = new this.$RongIMLib.SightMessage({
							sightUrl: item.content.sightUrl, // "<视频资源的远程地址>",
							content: item.content.content, // "<缩略图base64>",
							duration: item.content.duration,
							size: item.content.size,
							name: item.content.name,
						});
						break;
					case "RC:FileMsg":
						message = new this.$RongIMLib.FileMessage({
							fileUrl: item.content.fileUrl, // "<视频资源的远程地址>",
							type: item.content.type, // "<缩略图base64>",
							size: item.content.size,
							name: item.content.name,
						});
						break;
					case "OL:Card":
						message = new this.$RongIMLib.CardMessage({
							content: "",
							info: item.content.info,
						});
						break;
					case "RC:HQVCMsg":
						message = new this.$RongIMLib.HQVoiceMessage({
							remoteUrl: item.content.remoteUrl,
							duration: item.content.duration,
						});
						break;
					default:
						break;
				}
				return message;
			},
			async sendMessage(conversation, message, options) {
				console.log(conversation, message, options);
				// 发送消息
				const res = await this.$RongIMLib.sendMessage(
					conversation,
					message,
					options
				);

				if (res.code === this.$RongIMLib.ErrorCode.SUCCESS) {
					this.$store.dispatch("upChatList", res.data);
					this.nextResult();
				}
			},
			// 发送成功
			nextResult() {
				switch (this.type) {
					case 1: // 分享名片到聊天
						this.handleToPage(this.newSelectList[0]);
						break;
					case 2: // 单选转发
						this.handleToPage(this.newSelectList[0]);
						break;
					case 3: // 多选转发
						if (this.isToPage) {
							this.handleToPage(this.newSelectList[0]);
						}
						break;
					default:
						break;
				}
			},
			// 跳转页面
			handleToPage(item) {
				if (item.conversationType == 1) {
					uni.redirectTo({
						url: `/pages/chat/PersonalChat?targetId=${item.targetId}&backType=1`,
					});
				} else if (item.conversationType == 3) {
					var isModule = this.filterId.indexOf(item.targetId) > -1;
					if (item.info.moduleType == 1) {
						uni.redirectTo({
							url: `/pages/chat/GroupChat?isFriendGroup=true&groupId=${item.targetId}&isModule=true&backType=1`,
						});
					} else {
						uni.redirectTo({
							url: `/pages/chat/GroupChat?groupId=${item.targetId}&isModule=${isModule}&backType=1`,
						});
					}
				}
			},
			getRoomKeyLabel(item) {
				const obj = {
					label: '',
					color: ''
				}
				const val = item.info.moduleType
				switch (val) {
					case 1:
						obj.label = this.$t('customerObj.module5')
						obj.color = '#fe6600'
						break
					case 2:
						obj.label = this.$t('post.Transaction')
						obj.color = '#e6a23c'
						break
					case 3:
						obj.label = this.$t('customerObj.module7')
						obj.color = '#909399'
						break
					case 4:
						obj.label = this.$t('customerObj.module6')
						obj.color = '#000000'
						break
					case 5:
						obj.label = this.$t('discover.information')
						obj.color = '#8896b3'
						break
					case 6:
						obj.label = this.$t('discover.customer')
						obj.color = '#61bdb2'
						break

					default:
						break
				}
				return obj
			}
		},
		onLoad() {
			this.getPrePages()
		},
	};
</script>

<style lang="scss" scoped>
	.omit {
		text-overflow: -o-ellipsis-lastline;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		line-clamp: 1;
		-webkit-box-orient: vertical;
		word-wrap: break-word;
		white-space: pre-wrap;
		word-break: break-all;
	}

	.dating-tag {
		font-size: 24rpx;
		font-family: Source Han Sans CN;
		font-weight: 400;
		color: #fe6600;
		height: 40rpx;
		background: #ffffff;
		border: 2rpx solid #fe6600;
		border-radius: 8rpx;
		box-sizing: border-box;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0rpx 12rpx;
	}

	.wrapper {
		box-sizing: border-box;
		font-family: Source Han Sans CN;

		.u-nav-slot {
			font-size: 28rpx;
			font-weight: bold;
			color: #000000;
			opacity: 0.3;
			pointer-events: none;
		}

		.u-nav__active {
			pointer-events: all;
			color: #61bdb2;
			opacity: 1;
		}

		.select-number {
			text-align: center;
			font-size: 26rpx;
			color: #878787;
		}

		.search-content {
			position: relative;
			width: 690rpx;
			height: 76rpx;
			margin: 0 auto;
			margin-top: 24rpx;

			/deep/ .placeholderClass {
				font-size: 26rpx;
				font-family: Source Han Sans CN;
				font-weight: 400;
				color: #878787 !important;
				margin-left: 24rpx;
			}

			.serch-icon {
				position: absolute;
				top: 50%;
				left: 277rpx;
				color: #878787;
				font-size: 30rpx;
				transform: translateY(-50%);
			}
		}

		.tip-content-text {
			text-align: center;
			padding: 0 !important;
			line-height: 136rpx;
		}

		.tip-content {
			height: 136rpx;
			box-sizing: border-box;
			padding: 40rpx 30rpx 16rpx;

			&__text {
				font-size: 28rpx;
				color: #61bdb2;
			}

			.scroll-X {
				height: 100%;
				white-space: nowrap;

				.avatar {
					display: inline-block;
					margin-left: 30rpx;
					height: 100%;
				}

				.avatar0 {
					margin-left: 0;
				}
			}
		}

		.suspension-frame {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 20upx;
			width: 40upx;
			background: rgba($color: #000000, $alpha: 0.4);
			border-radius: 20upx;
			box-sizing: border-box;
			padding: 12upx 0;
			text-align: center;

			.text {
				font-size: 22upx;
				font-weight: 400;
				color: #ffffff;
				margin: 6upx 0;

				&.active {
					margin: 6rpx auto;
					width: 34upx;
					// height: 34upx;
					background: #61bdb2;
					border-radius: 17upx;
				}
			}
		}

		.scroll-Y {
			height: calc(100vh - 44px - 280rpx - var(--status-bar-height));
		}

		.chat-content {
			background-color: #f6f6f6;

			.chat-line {
				background-color: #fff;
				padding: 0 30rpx;
				border-bottom: 2rpx solid #f6f6f6;

				&__item {
					height: 120rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
				}

				.avatar-image {
					margin: 0 30rpx;
				}
			}
		}

		.avatar-image {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			text-align: center;
			line-height: 80rpx;
			font-size: 30upx;
			font-weight: 400;
			color: #ffffff;

			display: flex;
			align-items: center;
			justify-content: center;
		}

		.pinyin-line {
			width: 100%;
			height: 66upx;
			box-sizing: border-box;
			padding: 0 30upx;
			font-size: 24upx;
			font-weight: 400;
			color: #878787;
			line-height: 66upx;
			background: #f6f6f6;
		}
	}

	/deep/.scroll-X .uni-scroll-view-content {
		display: flex;
		align-items: center;
	}
</style>